package es.capgemini.extjsplugin.core;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.launching.JavaRuntime;

public class BlackmoreClassLoader extends ClassLoader {
	private IJavaProject javaProject;
	private static final String PROTOCAL_PREFIX = "file:///";

	public BlackmoreClassLoader(IJavaProject project) {
		super();
		if (project == null || !project.exists() || !project.isOpen())
			throw new IllegalArgumentException("Invalid javaProject");
		this.javaProject = project;
	}

	public BlackmoreClassLoader(IJavaProject project, ClassLoader classLoader) {
		super(classLoader);
		if (project == null || !project.exists() || !project.isOpen())
			throw new IllegalArgumentException("Invalid javaProject");
		this.javaProject = project;
	}

//	@SuppressWarnings("unchecked")
//	public Class findClass(String className) {
//		IClassFile classFile = null;
//		try {
//			IType type = javaProject.findType(className);
//			final IPackageFragment fragment = type.getPackageFragment();
//			
//			String java = className.substring(className.lastIndexOf('.') + 1) + ".class";
//			classFile = fragment.getClassFile(java);
//			
//			final byte[] buff = classFile.getBytes();
//			if (buff != null)
//			return defineClass(className, buff, 0, buff.length);
//		} catch (JavaModelException e) {
//			System.err.println("");
//			e.printStackTrace();
//		}
//		return null;
//	}
	public Class findClass(String className) {
		try {
			String[] classPaths = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
			URL[] urls = new URL[classPaths.length];
			for (int i = 0; i < classPaths.length; i++)
				urls[i] = new URL(PROTOCAL_PREFIX + computeForURLClassLoader(classPaths[i]));
			ClassLoader loader = new URLClassLoader(urls);
			Class classObject = loader.loadClass(className);
			return classObject;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String computeForURLClassLoader(String classpath) {
		if (!classpath.endsWith("/")) {
			File file = new File(classpath);
			if (file.exists() && file.isDirectory())
				classpath = classpath.concat("/");
		}
		return classpath;
	}

}
